package com.knowledge.review.designPatterns.behavioralpattern.mediatorpattern;

import lombok.AllArgsConstructor;
import lombok.Data;

// 抽象同事类
@AllArgsConstructor
public class Person {
    protected String name;
    protected MediatorCompany mediatorCompany;
}
// 房主
class HouseOwner extends Person {
    public HouseOwner(String name, MediatorCompany mediatorCompany) {
        super(name, mediatorCompany);
    }
    // 联络方法
    public void connection(String message) {
        mediatorCompany.connection(this, message);
    }
    // 获取消息
    public void getMessage(String message) {
        System.out.println("房主" + name + "获取到的信息:" + message);
    }
}
// 租客
class Tenant extends Person {
    public Tenant(String name, MediatorCompany mediatorCompany) {
        super(name, mediatorCompany);
    }
    public void connection(String message) {
        mediatorCompany.connection(this, message);
    }
    public void getMessage(String message) {
        System.out.println("租客" + name + "获取到的信息:" + message);
    }
}
// 中介公司(中介者)
@Data
class MediatorCompany {
    private HouseOwner houseOwner;
    private Tenant tenant;
    public void connection(Person person, String message) {
        // 房主需要通过中介获取租客信息
        if (person.equals(houseOwner)) {
            this.tenant.getMessage(message);
        } else { // 反之租客通过中介获取房主信息
            this.houseOwner.getMessage(message);
        }
    }
}

class Test{
    // 测试
    public static void main(String[] args){
        // 先创建三个角色，中介公司，房主，租客
        MediatorCompany mediatorCompany = new MediatorCompany();
        // 房主和租客都在同一家中介公司
        HouseOwner houseOwner = new HouseOwner("张三", mediatorCompany);
        Tenant tenant = new Tenant("李四", mediatorCompany);
        // 中介公司获取房主和租客的信息
        mediatorCompany.setHouseOwner(houseOwner);
        mediatorCompany.setTenant(tenant);
        // 房主和租客都在这家中介公司发布消息，获取到对应的消息
        tenant.connection(tenant.name + "想租一房一厅!");
        houseOwner.connection(houseOwner.name + "这里有!来看看呗!");
        // 测试结果
        // 房主张三获取到的信息:李四想租一房一厅!
        // 租客李四获取到的信息:张三这里有!来看看呗!
    }
}